<?php 
namespace app\admin\controller;
class Block extends Common {

	public function index(){
		$blocks = \Ebcms::db() -> select('block', '*');
		$groups = [];
		foreach ($blocks as $key => $value) {
			if (!isset($groups[$value['group']])) {
				$groups[$value['group']] = [];
			}
			$groups[$value['group']][] = $value;
		}
		$this -> assign('groups', $groups);
		return $this -> html($this -> fetch());
	}

	public function add(){
		if (\Ebcms::isPost()) {
			$type = \mylib\Input::post('type');
			\Ebcms::db() -> insert('block', [
				'group'=>\mylib\Input::post('group'),
				'title'=>\mylib\Input::post('title'),
				'name'=>\mylib\Input::post('name'),
				'value'=>\mylib\Input::post('value'),
				'type'=>\mylib\Input::post('type'),
				'expire'=>\mylib\Input::post('expire'),
				'tips'=>\mylib\Input::post('tips'),
			]);
			return $this -> success('操作成功！', \mylib\Route::buildUrl('/admin/block/index'));
		}else{
			$type = \mylib\Input::get('type');
			$this -> assign('type', $type);
			return $this -> html($this -> fetch());
		}
	}

	public function edit(){
		if (\Ebcms::isPost()) {
			\Ebcms::db() -> update('block', [
				'group'=>\mylib\Input::post('group'),
				'title'=>\mylib\Input::post('title'),
				'name'=>\mylib\Input::post('name'),
				'expire'=>\mylib\Input::post('expire'),
				'value'=>\mylib\Input::post('value'),
				'tips'=>\mylib\Input::post('tips'),
			], [
				'id'=>\mylib\Input::post('id')
			]);
			return $this -> success('操作成功！', \mylib\Route::buildUrl('/admin/block/index'));
		}else{
			$block = \Ebcms::db() -> get('block', '*', ['id'=>\mylib\Input::get('id')]);
			$this -> assign('block', $block);
			return $this -> html($this -> fetch());
		}
	}

	public function del(){
		if (\Ebcms::isAjax()) {
			\Ebcms::db() -> delete('block', [
				'id'=>\mylib\Input::post('id'),
			]);
			return $this -> success('操作成功！');
		}
	}

	public function refresh(){
		if (\Ebcms::isAjax()) {
			$blocks = \Ebcms::db() -> select('block', '*');
			foreach ($blocks as $key => $value) {
				\mylib\Cache::delete('block_' . md5($value['name']));
			}
			return $this -> error('已刷新所有碎片！');
		}
	}
}